<script>
	/**
	 * tabBar页面路径列表 (用于链接跳转时判断)
	 * tabBarLinks为常量, 无需修改
	 */
	const tabBarLinks = ["pages/index/index", "pages/community/index", "pages/user/index"]; // 站点配置文件
	// , "pages/message/index"

	// import TIM from 'tim-wx-sdk';
	// import TIMUploadPlugin from 'tim-upload-plugin';
	// import TIMProfanityFilterPlugin from 'tim-profanity-filter-plugin';


	// package.JSON: 
	// "@tencentcloud/chat": "^3.2.3",
	// "tim-profanity-filter-plugin": "^1.0.0",
	// "tim-upload-plugin": "^1.3.0",
	// "tim-wx-sdk": "^2.27.5",


	import siteinfo from "./siteinfo.js"; // 工具类
	import util from "./utils/util.js";


	// #ifdef H5
	// import amap from '@/utils/amap.js';
	import AMap from '@/utils/amap-wx.130.js'
	// #endif



	//微信小程序要调用的js文件
	// #ifdef MP  
	import amap from '@/utils/amap-wx.130.js'
	const amapObject = new amap.AMapWX({
		key: '9b7d034f179bdea3390055449ac2ea03',
		timeout: 10000,
	})
	// #endif



	import {
		isWeixin
	} from "./utils/verify.js";


	// #ifdef APP-PLUS
	import checkUpdate from "@/uni_modules/uni-upgrade-center-app/utils/check-update";
	import {
		handleError
	} from "vue";
	// #endif

	export default {
		/**
		 * 全局变量
		 */
		globalData: {
			toast: "",
			navigateToLoginLock: false, //登录页面跳转锁
			SDKAppID: 1600016041,
			user_id: null,
			UserInfo: null,
			register: {},
			router_base: "h5", // 运行的基础路径，h5/#
			// api地址
			// #ifdef H5
			// api_root: siteinfo.siteroot + "/api",
			api_root: siteinfo.siteroot,
			// #endif

			// #ifndef H5
			api_root: siteinfo.siteroot,
			// #endif
			app_name: "",
			app_version: util.appVersion(),
			platform: uni.getSystemInfoSync().platform,
			token: '',
			isLogin: false,
			bind_Phone: false,
			heightMode: "", // 海报的高度模式
			heightValue: "", // 设备高度值,
			heightPx: "", // 设备高度值（px）,
			widthPx: "", // 设备宽度值（px）,
			safeAreaBottom: "", // 设备安全区的高度（px）,
			statusBarHeight: "", // 设备顶部导航高度（px）,
			tabBarHeight: "", //tabber高度
			systemInfo: uni.getSystemInfoSync(),

			//问卷倒计时相关
			timer: null,
			countdown: 30,
			questionnaire: false,

			//会话未读总数
			totalUnreadCount: 0,
			//会话列表
			conversationList: [],
			topBar: {
				statusBarHeight: 0,
				navBarHeight: 0,
				topBarHeight: 0,
			},
			menuButtonRect: {},
			tabBar: [{
					pagePath: tabBarLinks[0],
					text: '首页',
					name: 'home',
					iconPath: "/static/images/tabbar/home.png",
					selectedIconPath: "/static/images/tabbar/home_active.png"
				},
				{
					pagePath: tabBarLinks[1],
					text: '找人',
					name: 'community',
					iconPath: '/static/images/tabbar/community.png',
					selectedIconPath: '/static/images/tabbar/community_active.png'
				},
				// {
				// 	pagePath: tabBarLinks[2],
				// 	text: '消息',
				// 	name: 'message',
				// 	iconPath: '/static/images/tabbar/message.png',
				// 	selectedIconPath: '/static/images/tabbar/message_active.png',
				// },
				{
					pagePath: tabBarLinks[3],
					text: '我的',
					name: 'user',
					iconPath: '/static/images/tabbar/user.png',
					selectedIconPath: '/static/images/tabbar/user_active.png',
				}
			]
		},
		/**
		 * 生命周期函数--监听小程序初始化
		 */
		onLaunch(e) {
			let _this = this; // 小程序主动更新

			// #ifdef MP-WEIXIN
			_this.updateManager(); // 小程序启动场景
			// #endif

			// #ifdef H5
			if (0 == Object.keys(e.query).length) {
				e.query = util.query();
			}
			// #endif

			_this.onStartupScene(e.query);
			_this.requireConfig();

			// #ifdef APP-PLUS
			checkUpdate();
			// push.config(_this);
			// #endif

			//获取导航条高度
			_this.getTopBarHeight();

			let user_info = uni.getStorageSync('user_info');
			let token = uni.getStorageSync('token');
			_this.globalData.token = token
			_this.globalData.UserInfo = user_info
			_this.globalData.isLogin = !!user_info
			

			// 获取设备高度
			uni.getSystemInfo({
				success: (res) => {
					this.globalData.heightMode = res.windowHeight >= 800 ? "big" : "small";
					this.globalData.heightValue = res.windowHeight >= 800 ? "1020rpx" : "900rpx";
					this.globalData.heightPx = res.windowHeight;
					this.globalData.widthPx = res.windowWidth;
					let safeArea = res.safeArea;
					let windowHeight = res.windowHeight;
					let screenHeight = res.screenHeight;
					let safeAreaBottom = screenHeight - safeArea.bottom;
					let tabBarHeight = screenHeight - windowHeight;
					this.globalData.safeAreaBottom = safeAreaBottom;
					this.globalData.tabBarHeight = tabBarHeight;
					this.globalData.statusBarHeight = res.statusBarHeight;
					this.$store.commit("changeRpxSize", res.windowWidth / 750);
					// console.log("底部安全区的高度", safeAreaBottom);
					// console.log("顶部导航的高度", res.statusBarHeight);

				}
			});

			// 监听键盘弹起关闭 获取软件键盘高度
			uni.onKeyboardHeightChange((res) => {
				// if (this.$store.state.keyHeight) {
				// 	return
				// }
				this.$store.commit("changeKeyHeight", res.height);
			})
			const value = uni.getStorageSync('guide');
			if (value) {
				// 如果已经有，直接去home首页
				uni.switchTab({
					url: '/pages/index/index',
					success: (res) => {
						// console.log(res);
						this.globalData.timer = setInterval(() => {
							this.showtime()
						}, 1000)
					},
					fail: (err) => {
						// console.log(err);
					}
				});
			} else {
				uni.setStorageSync('guide', 'guide')
				// 没有值，跳到引导页
				uni.redirectTo({
					url: '/pages/index/guide',
					success: (res) => {
						// console.log(res);
					},
					fail: (err) => {
						// console.log(err);
					}
				});
			}
		},
		// 监听仓库全局变量loading显示隐藏 toast

		/**
		 * 当小程序启动，或从后台进入前台显示，会触发 onShow
		 */
		onShow(options) {
			//im登录
			this.chatLogin();
			// setTimeout(()=>{
			// 	this.$store.commit("changeLoadingShow",true);
			// },5000);
			// console.log(" %c PENG一下 ", "font-size:36px;color:#A7F517;background-color: #282D2D;font-style:oblique;")
		},
		onHide() {
			uni.removeStorageSync('mov-top');
			// let promise = uni.$TUIKit.logout();
			// promise.then(res => {
			// 	this.$store.commit('reset')
			// }).catch(err => {
			// 	console.log('退出失败')
			// });
		},
		mounted() {
			// setTimeout(()=>{
			// 	this.$store.commit("changeLoadingShow",true);
			// },5000)

			// 注册上传
			// uni.$TUIKit.registerPlugin({
			// 	'tim-upload-plugin': TIMUploadPlugin
			// });
			// // 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
			// uni.$TUIKit.on(uni.$TUIKitEvent.SDK_READY, this.onSDKReady, this);
			// // 收到新消息
			// uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.onReceiveMessage);

			// // 会话列表更新
			// uni.$TUIKit.on(uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED, event => {
			// 	this.$store.commit("updateConversationList", event.data);
			// });
			// // 监听被踢下线
			// uni.$TUIKit.on(uni.$TUIKitEvent.KICKED_OUT, this.onKickedOut, this);

			// // 会话未读总数
			// uni.$TUIKit.on(uni.$TUIKitEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, event => {
			// 	this.$store.commit("onTotalUnreadMessageCountUpdated", event.data);
			// });
		},
		methods: {
			// sdk 加载完
			onSDKReady({
				name
			}) {
				// const isSDKReady = name === uni.$TUIKitEvent.SDK_READY ? true : false;
				//自动监听并更新 sdk 的ready 状态 （未登录是 notReady  登录后是ready）
				// this.$store.commit("toggleIsSDKReady", isSDKReady);
			},
			onReceiveMessage({
				data: messageList
			}) {
				// this.$store.commit("pushCurrentMessageList", messageList);
			},
			getChstUserSig() {
				return new Promise((resolve, reject) => {
					this._post_form(
						"/client/im/create-user-sig", null,
						(result) => {
							this.globalData.UserInfo.userSig = result.data.userSig
							this.chatLogin(result.data.userSig)
						}, null, () => {
							resolve();
						}
					);
				});
			},
			chatLogin() {
				// console.log(this.globalData.UserInfo);
				if (!this.globalData.UserInfo) {
					return
				}
				// uni.$TUIKit.login({
				// 	userID: this.globalData.UserInfo.authInfo.userId,
				// 	userSig: this.globalData.UserInfo.userSig
				// }).then((res) => {
				// 	//登录成功后 更新登录状态
				// 	this.$store.commit("toggleIsLogin", true);
				// 	//tim 返回的用户信息
				// 	uni.setStorageSync('userTIMInfo', JSON.stringify(res.data))
				// 	console.log(res, "登录了")
				// }).catch((error) => {
				// 	console.log(error, "报错了")
				// })
			},

			// 踢下线
			onKickedOut() {
				this.showError("您被踢下线，请重新登录", () => {
					this.removeLogin()
				});
			},
			// 0元购倒计时
			get_date() {
				var day_date = new Date(new Date(new Date().getTime() + 24 * 60 * 60 * 1000).setHours(0, 0, 0, 0))
					.getTime(); //指定今晚0点求时间戳
				var now_time = new Date().getTime(); //获取当前时间戳
				var hours = Math.floor((day_date - now_time) / 60 / 60 / 1000).toString().padStart(2, 0);
				var minius = Math.floor((day_date - now_time) / 60 / 1000 % 60).toString().padStart(2, 0);
				var second = Math.floor((day_date - now_time) / 1000 % 60).toString().padStart(2, 0);
				return (hours + ':' + minius + ':' + second)
			},

			// 问卷调查
			showtime() {
				if (this.globalData.countdown > 0) {
					this.globalData.countdown--; // 每秒减1
				} else {
					clearInterval(this.globalData.timer); // 倒计时结束，清除定时器
					this.globalData.questionnaire = true
				}
			},
			watch(method, istr) {
				var obj = this.globalData
				console.log('watch....');
				Object.defineProperty(obj, istr, {
					configurable: true,
					enumerable: true,
					set: function(value) {
						console.log('set', value);
						method(value)
					},
					get: function(value) {
						return value
					}
				})
			},

			// 获取导航条相关高度
			getTopBarHeight: function() {
				let statusBarHeight = uni.getSystemInfoSync().statusBarHeight; // 状态栏的高度
				let topBarHeight = 0;
				let navBarHeight = 0;
				// #ifdef MP-WEIXIN
				let menuButtonRect = uni.getMenuButtonBoundingClientRect(); // 胶囊的坐标
				if (menuButtonRect) {
					topBarHeight = menuButtonRect.top + menuButtonRect.bottom - statusBarHeight; // 状态栏+导航条的高度
					navBarHeight = topBarHeight - statusBarHeight; // 导航条的高度
				}
				this.globalData.menuButtonRect = menuButtonRect;
				// #endif

				this.globalData.topBar = {
					statusBarHeight: statusBarHeight,
					navBarHeight: navBarHeight,
					topBarHeight: topBarHeight,
				};
			},
			// 请求App/H5配置项（图片等）
			requireConfig() {
				// 先读取本地配置数据
				let config = uni.getStorageSync("config");
				this.setConfigToGlobal(config);

				uni.setStorageSync("config", "config");
				this.setConfigToGlobal("config");
			},
			// 全局配置信息加入globalData
			setConfigToGlobal(data) {},
			/**
			 * 小程序启动场景
			 */
			onStartupScene(query) {
				// 获取场景值
				let scene = this.getSceneData(query);
				// 记录推荐人id
				let refereeId = query.referee_id ? query.referee_id : scene.uid;
				if (refereeId > 0) {
					this.saveRefereeId(refereeId);
				}
			},


			/**
			 * 记录推荐人id
			 */
			saveRefereeId(refereeId) {
				if (!uni.getStorageSync("referee_id")) {
					uni.setStorageSync("referee_id", refereeId);
				}
			},
			//文本内容审核  1 资料；2 评论；3 论坛；
			checkMessage(messageContent, scene) {
				return new Promise((resolve, reject) => {
					app._post_form(
						"/client/input-check/check-message", {
							messageContent: messageContent,
							scene: scene
						},
						(result) => {
							let res = result.data
							resolve(res);
						}, null, () => {
							resolve(false);
						}
					);
				});
			},

			/**
			 * 获取场景值(scene:k:v,k:v)
			 */
			getSceneData(query) {
				return query.scene ? util.scene_decode(query.scene) : {};
			},

			/**
			 * 获取场景值(scene:k=v&k=v)
			 */
			aj_getSceneData(query) {
				return query.scene ? util.aj_scene_decode(query.scene) : {};
			},

			navigateToLogin() {
				if (this.globalData.navigateToLoginLock) {
					return;
				}
				this.globalData.navigateToLoginLock = true;
				// 保存当前页面
				let pages = getCurrentPages();
				if (pages.length) {
					let currentPage = pages[pages.length - 1];
					let route = currentPage.route;
					if ("page_account/login/login" != route) {
						let localLastPage = uni.getStorageSync('goCurrentPage');
						if (!localLastPage) {
							uni.setStorageSync("goCurrentPage", `${route}`);
						}
					} else {
						this.globalData.navigateToLoginLock = false;
						return false;
					}
				} // 跳转授权页面

				uni.navigateTo({
					url: "/page_account/login/login",
					complete: () => {
						setTimeout(() => {
							this.globalData.navigateToLoginLock = false;
						}, 1000);
					},
				});
			},
			beNavigateBack(params) {
				const pages = getCurrentPages()
				if (pages.length === 1) {
					if (typeof params === 'number') {
						history.go(-params)
					} else {
						history.back()
					}
				} else {
					uni.navigateBack()
				}
			},

			/**
			 * 执行用户登录
			 */
			doLogin() {
				this.navigateToLogin();
			},

			/**
			 * 当前用户id
			 */
			getUserId() {
				return uni.getStorageSync("user_id");
			},

			/**
			 * 显示成功提示框
			 */
			showSuccess(msg, callback) {
				uni.showToast({
					title: msg,
					icon: "success",
					mask: true,
					duration: 1500,
					success() {
						if (callback) {
							setTimeout(function() {
								callback();
							}, 1500);
						}
					},
				});
			},

			/**
			 * 显示成功提示框
			 */
			showSuccessWithDuration(duration, msg, callback) {
				setTimeout(function() {
					uni.showToast({
						title: msg,
						icon: "success",
						mask: true,
						duration: duration,
						success() {
							if (callback) {
								setTimeout(function() {
									callback();
								}, duration);
							}
						},
					});
				}, 200);
			},

			/**
			 * 提示toast，延迟是为了兼容真机
			 * @param {*} title 信息
			 */
			showToast(title, duration = 1500) {
				setTimeout(() => {
					uni.showToast({
						icon: "none",
						title: title,
						duration: duration,
					});
				}, 200);
			},
			//是否实名
			hadAuthentication() {
				// const value = uni.getStorageSync('hadAuthentication');
				return true;
			},
			/**
			 * 显示失败提示框
			 */
			showError(msg, callback) {
				uni.showModal({
					title: "友情提示",
					content: msg,
					showCancel: false,
					success(res) {
						if (callback) {
							callback();
						}
					},
				});
			},
			failCode(res) {
				let _this = this; // 构造请求参数
				if (res.code == 40001) {
					// 登录态失效, 重新登录
					_this.removeLogin()
					return false;
				} else if (res.code == 40003) {
					_this.showError(res.msg);
					return false;
				} else if (res.code == 401) {
					_this.showError(res.msg || "系统繁忙", () => {
						_this.removeLogin()
					});
					return false;
				} else if (res.data == null || (res.code != 0 && res.code != 200)) {
					_this.showError(res.msg || "系统繁忙");
					return false;
				}
			},
			//注销登录IM
			outLoginIM() {
				let promise = uni.$TUIKit.logout();
				promise.then(res => {
					this.$store.commit('reset')
				}).catch(err => {
					console.log('退出失败')
				});
			},
			/**
			 * 清除登录状态
			 */
			removeLogin() {
				let _this = this; // 构造请求参数
				uni.removeStorageSync('token');
				uni.removeStorageSync('user_info');
				uni.removeStorageSync('coupon_detail');
				_this.globalData.UserInfo = {}
				_this.globalData.isLogin = false
				_this.globalData.token = ''
				_this.globalData.bind_Phone = false
				// _this.outLoginIM()
				_this.doLogin();
			},
			/**
			 * 判断token是否过期
			 */
			judgeToken(url) {
				let _this = this; // 构造请求参数
				var expiredTime = +new Date() + 28800 * 1000
				var expiredTimes = uni.getStorageSync('expiresIn') || expiredTime;
				var noToken = ['/client/index/address/change', '/client/index/banner', '/client/index/peng-user/detail',
					'/client/index/peng-user/page', '/client/peng-timetable/select', '/client/forum/page',
					'/client/forum/personnel-page', '/client/forum-topic/topic-list', '/client/forum-topic/topic-page',
					'/client/forum-comment/query-page', '/client/forum-comment/query-replay-page',
					'/client/forum-topic/forum-detail', '/client/forum-topic/submit-forum-view',
					'/client/forum-topic/query-topic-view-num', '/client/forum/personnel-forum-page',
					'/client/qr/create-wx-code', '/client/coupon/query/coupon-toast'
				];
				var loginUrl = '/client/noToken/login'
				var now = +new Date()
				//登录接口 return
				if (loginUrl == url) {
					return true;
				}
				if (!(noToken.indexOf(url) >= 0)) {
					// 如果需要登录
					// 判断token是否过期，过期强制登出，不过期，正常走下一步
					if (expiredTimes - now < 0) {
						// token失效，重新获取
						this.removeLogin()
						return false;
					} else {
						// token有效，不需要操作
						// 获取用户 token
						let userToken = _this.globalData.token
						if (!userToken) {
							this.removeLogin()
							return false;
						} else {
							return true;
						}
					}
				} else {
					return true;
				}
			},

			/**
			 * get请求
			 */
			_get(url, data, success, fail, complete, check_login) {
				let _this = this; // 构造请求参数
				let expir = _this.judgeToken(url)
				if (!expir) {
					return
				}
				data = data || {};
				// 构造get请求
				let header = {}
				if (_this.globalData.bind_Phone || _this.globalData.isLogin) {
					header = {
						token: _this.globalData.token ? 'Bearer ' + _this.globalData.token : {}
					}
				}

				let request = function() {
					let requestUrl = _this.globalData.api_root + url;

					uni.request({
						url: requestUrl,
						header: header,
						data: data,
						success(res) {
							if (res.data.code == 40001) {
								// 登录态失效, 重新登录
								_this.removeLogin()
								return false;
							} else if (res.data.code == 40003) {
								_this.showError(res.data.msg, function() {
									if (fail) {
										fail(res);
									}
								});
								return false;
							} else if (res.data.code == 401) {
								_this.showError(res.data.msg || "系统繁忙", () => {
									_this.removeLogin()
								});
								return false;
							} else if (res.data.data == null || (res.data.code != 0 && res.data.code != 200)) {
								_this.showError(res.data.msg || "系统繁忙");

								return false;
							}

							if (success) {
								success(res.data);
							}
						},
						fail(res) {
							_this.showError(res.errMsg, function() {
								if (fail) {
									fail(res);
								}
							});
						},
						complete(res) {
							if (complete) {
								complete(res);
							}
						},
					});
				};
				// 判断是否需要验证登录
				if (check_login) {
					_this.doLogin(request);
				} else {
					request();
				}
			},

			/**
			 * post提交
			 */
			_post_form(url, data, success, fail, complete, successFail, isShowNavBarLoading) {
				let _this = this;
				let expir = _this.judgeToken(url)
				if (!expir) {
					return
				}
				let header = {}
				if (_this.globalData.bind_Phone || _this.globalData.isLogin || url == '/client/coupon/query/coupon-detail') {
					header = {
						token: _this.globalData.token ? 'Bearer ' + _this.globalData.token : {}
					}
				}
				let requestUrl = _this.globalData.api_root + url;
				uni.request({
					url: requestUrl,
					method: "POST",
					header: header,
					data: data,
					success(res) {
						if (res.data.code == 40001) {
							// 登录态失效, 重新登录
							uni.removeStorageSync('token');
							uni.removeStorageSync('user_info');
							_this.globalData.UserInfo = {}
							_this.globalData.isLogin = false
							_this.globalData.token = ''
							_this.doLogin();
							return false;
						} else if (res.data.code == 40003) {
							_this.showError(res.data.msg, function() {
								if (fail) {
									fail(res);
								}
							});
							return false;
						} else if (res.data.code == 401) {
							_this.showError(res.data.msg || "系统繁忙", () => {
								uni.removeStorageSync('token');
								uni.removeStorageSync('user_info');
								_this.globalData.UserInfo = {}
								_this.globalData.isLogin = false
								_this.globalData.token = ''
								_this.doLogin();
							});
							return false;
						} else if (res.data.data == null || (res.data.code != 0 && res.data.code != 200)) {
							_this.showError(res.data.msg || "系统繁忙");

							if (successFail) {
								successFail(res)
							}
							return false;
						}

						if (success) {
							success(res.data);
						}
					},
					fail(res) {
						console.log('fail', res);
						_this.showError(res.errMsg, function() {
							if (fail) {
								fail(res);
							}
						});
					},
					complete(res) {
						uni.hideNavigationBarLoading(); // wx.hideLoading();

						if (complete) {
							complete(res);
						}
					},
				});
			},

			/**
			 * 将本地资源上传到开发者服务器
			 * url
			 * filePath 要上传文件资源的路径
			 * name 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
			 * formData HTTP 请求中其他额外的 form data
			 * complete 请求完成
			 */
			_uploadFile(url, filePath, name, formData, success, fail, complete) {
				formData = formData || {};
				let header = {}

				if (this.globalData.token) {
					header = {
						token: 'Bearer ' + this.globalData.token,
					}
				}
				uni.uploadFile({
					url: this.globalData.api_root + url,
					filePath: filePath,
					name: name,
					formData: formData,
					header: header || {},
					complete: (res) => {
						let result = typeof res.data === "object" ? res.data : JSON.parse(res.data);
						if (0 == result.code || 200 == result.code) {
							success && success(result.data);
						} else {
							fail && fail(result.msg);
						}
						complete && complete();
					},
				});
			},
			// 上传图片
			_uploadImage(filePath, formData, success, fail, complete) {
				this._uploadFile("/client/file/anyone/upload", filePath, "file", formData, success, fail, complete);
			},

			/**
			 * 小程序主动更新
			 */
			updateManager() {
				if (!uni.canIUse("getUpdateManager")) {
					return false;
				}

				const updateManager = uni.getUpdateManager();
				updateManager.onCheckForUpdate(function(res) {
					// 请求完新版本信息的回调
					// console.log(res.hasUpdate)
				});
				updateManager.onUpdateReady(function() {
					uni.showModal({
						title: "更新提示",
						content: "新版本已经准备好，即将重启应用",
						showCancel: false,
						success(res) {
							if (res.confirm) {
								// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
								updateManager.applyUpdate();
							}
						},
					});
				});
				updateManager.onUpdateFailed(function() {
					// 新的版本下载失败
					uni.showModal({
						title: "更新提示",
						content: "新版本下载失败",
						showCancel: false,
					});
				});
			},

			/**
			 * 获取tabBar页面路径列表
			 */
			getTabBarLinks() {
				return tabBarLinks;
			},

			/**
			 * 跳转到指定页面
			 * 支持tabBar页面
			 * 支持h5页面
			 */
			navigationTo(url) {
				if (!url || url.length == 0) {
					return false;
				}

				let tabBarLinks = this.getTabBarLinks(); // tabBar页面
				if (tabBarLinks.indexOf(url) > -1) {
					uni.switchTab({
						url: "/" + url,
					});
				} else {
					var position = url.indexOf("http");
					if (0 === position) {
						// h5页面
						// #ifdef H5
						window.open(url, "_self");
						// #endif
						// #ifndef H5
						uni.navigateTo({
							url: "/pages/h5/index?src=" + encodeURIComponent(url),
						});
						// #endif
					} else {
						// 小程序页面
						uni.navigateTo({
							url: "/" + url,
						});
					}
				}
			},
			navigationBack() {
				uni.navigateBack();
			},

			/**
			 * 生成转发的url参数
			 */
			getShareUrlParams(params) {
				let _this = this;
				return util.urlEncode(
					Object.assign({
							referee_id: _this.getUserId(),
						},
						params
					)
				);
			},

			/**
			 * 发起微信支付
			 */
			wxPayment(option) {
				let options = Object.assign({
						payment: {},
						success: () => {},
						fail: () => {},
						complete: () => {},
					},
					option
				);
				uni.requestPayment({
					timeStamp: options.payment.timeStamp,
					nonceStr: options.payment.nonceStr,
					package: options.payment.package,
					signType: options.payment.signType,
					paySign: options.payment.paySign,
					success(res) {
						options.success(res);
					},
					fail(res) {
						options.fail(res);
					},
					complete(res) {
						options.complete(res);
					},
				});
			},
			/**
			 * 微信内嵌浏览器支付
			 */
			wxH5Payment(option) {
				let options = Object.assign({
						payment: {},
						success: () => {},
						fail: () => {},
						complete: () => {},
					},
					option
				);
				WeixinJSBridge.invoke("getBrandWCPayRequest", options.payment, function(res) {
					// console.log(res.err_msg);
					switch (res.err_msg) {
						case "get_brand_wcpay_request:ok":
							options.success(res);
							break;
						case "get_brand_wcpay_request:cancel":
							// 支付取消
							options.fail(res);
							break;
						case "get_brand_wcpay_request:fail":
							// 支付失败
							options.fail(res);
							break;
						default:
							// 调用支付JSAPI缺少参数
							break;
					}
				});
			},
			/**
			 * H5支付，实现在非微信浏览器（如QQ浏览器、谷歌浏览器、Safari等）中使用微信支付的场景
			 * @param {Object} mweb_url 为拉起微信支付收银台的中间页面，可通过访问该url来拉起微信客户端，完成支付,mweb_url的有效期为5分钟
			 */
			H5Payment(mweb_url) {
				window.open(mweb_url, "_self");
			},

			/**
			 * 验证登录
			 */
			checkIsLogin(callback) {
				let token = uni.getStorageSync("token");
				let userId = uni.getStorageSync("user_id");
				if (token != "" && userId != "") {
					this._get(
						"page/checkToken", {
							token,
						},
						(result) => {
							typeof callback === "function" && callback(result.data);
						}
					);
				} else {
					typeof callback === "function" && callback(false);
				}
			},
			/**
			 * 微信h5静默登录
			 * @param {Object} openid openid
			 * @param {Object} code code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期
			 * @param {Object} inviteCode 邀请码
			 */
			wechatH5Login(openid, code, inviteCode) {
				let param = {
					from: "h5",
					referee_id: uni.getStorageSync("referee_id"),
				};
				if (code) {
					param.code = code;
				}
				if (openid) {
					param.openid = openid;
				}
				if (inviteCode) {
					param.inviteCode = inviteCode;
				}

				this._post_form(
					"user/login",
					param,
					(result) => {
						// 记录token user_id
						uni.setStorageSync("token", result.data.token);
						uni.setStorageSync("user_id", result.data.user_id);
						uni.setStorageSync("openid", result.data.openid);
						// 不存在openid，刷新当前页面
						window.location.href = location.href.split("#")[0];
					},
					false,
					() => {}
				);
			},
			/**
			 * 获取微信登录code
			 */
			getCode() {
				return new Promise((resolve, reject) => {
					uni.login({
						success: (res) => {
							resolve(res.code);
						},
						fail: () => {
							this.showError("微信登录失败！");
							reject("微信登录失败！");
						},
					});
				});
			},

			// 登录成功回调
			doLoginSuccessCallback() {
				if (this.loginSuccessCallback) {
					// 返回从哪个页面跳转的登录
					let page = uni.getStorageSync("goCurrentPage");
					this.loginSuccessCallback(page);
				}
			},
			/**
			 * 上一个页面
			 */
			lastPage: function() {
				return this.prePage(1);
			},

			/**
			 * 授权登录，getUserProfile方式
			 */
			getUserProfile(res, callback) {
				let App = this;
				uni.showLoading({
					title: "正在登录",
					mask: true,
				});
				App.getCode().then((code) => {
					// 发送用户信息
					App._post_form(
						"user/login", {
							code: code,
							// user_info: JSON.stringify(res.userInfo),
							encrypted_data: res.encryptedData,
							iv: res.iv,
							signature: res.signature,
							referee_id: uni.getStorageSync("referee_id"),
						},
						(result) => {
							const {
								token,
								user_id
							} = result.data;
							if (-10000 == user_id) {
								// App.navigationTo(`page_account/login/register?openid=${token}`);
							} else {
								// 记录token user_id
								uni.setStorageSync("token", token);
								uni.setStorageSync("user_id", user_id); // 执行回调函数

								if (callback) {
									callback();
								}

								this.doLoginSuccessCallback();
							}
						},
						false,
						() => {
							uni.hideLoading();
						}
					);
				});
			},

			/**
			 * 授权登录
			 */
			getUserInfo(e, callback) {
				let App = this;

				if (e.detail.errMsg !== "getUserInfo:ok") {
					return false;
				}

				uni.showLoading({
					title: "正在登录",
					mask: true,
				}); // 执行微信登录

				uni.login({
					success(res) {
						// 发送用户信息
						App._post_form(
							"user/login", {
								code: res.code,
								user_info: e.detail.rawData,
								encrypted_data: e.detail.encryptedData,
								iv: e.detail.iv,
								signature: e.detail.signature,
								referee_id: uni.getStorageSync("referee_id"),
							},
							(result) => {
								// 记录token user_id
								uni.setStorageSync("token", result.data.token);
								uni.setStorageSync("user_id", result.data.user_id); // 执行回调函数

								if (callback) {
									callback();
								}

								this.doLoginSuccessCallback();
							},
							false,
							() => {
								uni.hideLoading();
							}
						);
					},
				});
			},


			/**
			 * 前面第几个页面
			 * @param {*} delta 第几个
			 */
			prePage: function(delta) {
				let pages = getCurrentPages();
				let count = pages.length;
				if (delta < count) {
					return pages[count - delta - 1];
				}
				return null;
			},
			//位置信息 腾讯
			async getLocationInfoGd() {
				return new Promise((resolve) => {
					//位置信息默认数据
					let location = {
						longitude: 0, // 经度
						latitude: 0, //纬度
						province: "", //坐标点所在省名称
						city: "", //坐标点所在城市名称
						area: "", //坐标点所在区
						street: "", //街道名称
						address: "", //poi地址信息
						status: "",
					};

					//h5开始
					// #ifdef H5
					//----------------------------------
					resolve({
						status: 'fail',
						value: '对不起，位置获取失败！'
					});
					return
					//----------------------------------
					AMap.plugin('AMap.Geolocation', function() {
						var geolocation = new AMap.Geolocation({
							enableHighAccuracy: true, //是否使用高精度定位，默认:true
							timeout: 10000, //超过10秒后停止定位，默认：5s
							buttonPosition: 'RB', //定位按钮的停靠位置
							buttonOffset: new AMap.Pixel(10,
								20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
							zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点

						});
						geolocation.getCurrentPosition(function(status, result) {
							let location = result
							console.log(location);
							if (status == 'complete') {
								if (!result.addressComponent) {
									resolve({
										status: 'fail',
										value: '对不起，位置获取失败！'
									});
									uni.showToast({
										'title': '对不起，位置获取失败！',
										'icon': 'none'
									})
								} else {
									location.status = 'success'
									resolve(result)
								}
							} else {
								resolve({
									status: 'fail',
									value: '对不起，位置获取失败！'
								});
								uni.showToast({
									'title': '对不起，位置获取失败！',
									'icon': 'none'
								})
							}
						});
					});
					// #endif
					//h5结束

					//app开始
					// #ifdef APP-PLUS
					uni.getLocation({
						// map组件默认为国测局坐标gcj02，调用 uni.getLocation返回结果传递给组件时，需指定 type 为 gcj02 
						type: 'gcj02',
						geocode: true,
						success: function(data) {
							resolve(data)
							console.log(data)
						},
						fail: function(err) {
							reject(err)
							console.log(err)
						},
						complete() {
							uni.hideLoading();
						}
					})
					setTimeout(() => {
						if (location.longitude == 0) {
							resolve({
								status: 'fail',
								value: '对不起，位置获取失败！'
							});
						}
					}, 3000)
					// #endif
					//app结束

					// 小程序开始
					// #ifdef MP
					// location.longitude = '120.13';
					// location.latitude = '';
					// location.province = '浙江省';
					// location.city = '杭州市';
					// location.area = '';
					// location.street = '';
					// location.status = "success";
					// let CityName = location.city + (location.area.length > 0 ? location
					// 	.area : location.street);
					// uni.setStorage({
					// 	key: 'City_Name',
					// 	data: CityName
					// });
					// resolve(location);
					// return false
					amapObject.getRegeo({
						success: (res) => {
							console.log(res);
							let info = res[0].regeocodeData;
							location.longitude = res[0].longitude;
							location.latitude = res[0].latitude;
							location.province = info.addressComponent.province;
							location.city = info.addressComponent.city.length > 0 ? info
								.addressComponent.city : info.addressComponent.province.length >
								0 ? info.addressComponent.province : '';
							location.area = info.addressComponent.district;
							location.street = info.addressComponent.township;
							location.status = "success";
							let CityName = location.city + (location.area.length > 0 ? location
								.area : location.street);
							uni.setStorage({
								key: 'City_Name',
								data: CityName
							});
							resolve(location);
						},
						fail: (err) => {
							console.log(err);
							uni.showToast({
								'title': '对不起，位置获取失败！',
								'icon': 'none'
							})
							resolve({
								status: 'fail',
								value: '对不起，位置获取失败！'
							});
						}
					})
					setTimeout(() => {
						if (location.longitude == 0) {
							resolve({
								status: 'fail',
								value: '对不起，位置获取失败！'
							});
						}
					}, 3000)
					// #endif
					//小程序结束
					// uni.getLocation({
					// 	type: "wgs84",
					// 	success(res) {

					// 	},
					// 	fail(err) {
					// 		uni.showToast({
					// 			'title': '对不起，获取位置失败！',
					// 			'icon': 'none'
					// 		})
					// 		resolve({
					// 			status: 'fail',
					// 			value: '对不起，获取位置失败！'
					// 		});
					// 	},
					// });
				});
			},
		},
	};
</script>

<style lang="scss">
	@import "/utils/iconfont-dy.css";
	@import '@/utils/common.scss';
</style>